package cqrtplm.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.hustcad.plm.basic.util.TyplmEntityBaseUtil;
import com.hustcad.plm.basic.util.TyplmViewConfigUtil;
import com.hustcad.plm.pdm.classification.model.dto.TyplmClassificationEntityDTO;
import com.hustcad.plm.pdm.classification.service.TyplmClassificationService;
import com.hustcad.plm.pdm.common.model.dto.ObjRenameDTO;
import com.hustcad.plm.pdm.common.model.dto.search.SearchConditionDTO;
import com.hustcad.plm.pdm.common.model.vo.search.ResultEntityVO;
import com.hustcad.plm.pdm.common.service.TyplmObjsRenameService;
import com.hustcad.plm.pdm.common.service.search.TyplmCommonSearchService;
import com.hustcad.plm.pdm.form.model.vo.PdmForm;
import com.hustcad.plm.pdm.form.model.vo.PdmFormColumn;
import com.hustcad.plm.pdm.form.model.vo.TyplmFormDataVO;
import com.hustcad.plm.pdm.form.service.TyFormDataExtService;
import com.hustcad.plm.pdm.form.service.TyplmDynamicFormService;
import com.hustcad.plm.pdm.iba.model.dto.SaveObjIBADTO;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeService;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeValueService;
import com.hustcad.plm.pdm.partbom.dto.PartBomTree;
import com.hustcad.plm.pdm.type.service.TyplmTypeService;
import com.hustcad.plm.pdm.user.service.TyplmOrgService;
import com.hustcad.plm.pdm.user.service.TyplmPrincipalService;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.dto.constraint.IbaDTO;
import com.ty.basic.entity.CTyEntityBaseDO;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.PrincipalEntity;
import com.ty.basic.entity.org.OrgDO;
import com.ty.basic.entity.part.PartDO;
import com.ty.basic.session.TyAccountContext;
import com.ty.basic.vo.AttributeVO;
import com.ty.basic.vo.TyAttributeDefMapVO;
import cqrtplm.common.CommonService;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.dto.FormDataDTO;
import cqrtplm.dto.PdmFormDTO;
import cqrtplm.entity.DeptRoleDO;
import cqrtplm.entity.DescribeSpliceRuleDO;
import cqrtplm.entity.ProjectDevOrderDO;
import cqrtplm.mapper.DeptRoleMapper;
import cqrtplm.mapper.ProjectDevOrderMapper;
import cqrtplm.mapper.RTAttributeCardMapper;
import cqrtplm.mapper.RTPartMapper;
import cqrtplm.mapper.RTTypeClassMapper;
import cqrtplm.service.RTClassificationService;
import cqrtplm.service.RTFormService;
import cqrtplm.vo.RTResultEntityVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RTFormServiceImpl implements RTFormService {
    @Resource
    private CommonService commonService;
    @Resource
    private TyFormDataExtService tyFormDataExtService;
    @Resource
    private TyplmAttributeValueService typlmAttributeValueService;
    @Resource
    private TyplmCommonSearchService typlmCommonSearchService;
    @Resource
    private RTTypeClassMapper typeClassMapper;
    @Resource
    private TyplmObjsRenameService typlmObjsRenameService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFormProperty(String workFlowContainerId) {
        List<IdentifierEntity> flowObjEntityList = commonService.getFlowObjListByWorkFlowContainer(new BigInteger(workFlowContainerId));
        List<SaveObjIBADTO> objWithIbaList = new ArrayList<>();
        for (IdentifierEntity entity : flowObjEntityList) {
            TyplmFormDataVO formDataVO = this.tyFormDataExtService.getFormDataDetail(entity.getOid());
            JSONObject formData = formDataVO.getFormdata();
            List<FormDataDTO> formDataDTOS = FormDataDTO.convertToFormDataDTO(formData);
            SaveObjIBADTO saveObjIBADTO = new SaveObjIBADTO();
            List<IbaDTO> ibaDTOList = new ArrayList<>();
            for (FormDataDTO formDataDTO : formDataDTOS) {
                String key = formDataDTO.getKey();
                Object value = formDataDTO.getValue();
                dealValue(key, value,ibaDTOList);
            }
            saveObjIBADTO.setObjIbaList(ibaDTOList);
            saveObjIBADTO.setCTyEntityBaseDO(new CTyEntityBaseDO(entity.getOid(), entity.getOtype()));
            objWithIbaList.add(saveObjIBADTO);
        }
        this.typlmAttributeValueService.batchSaveIBAByObjsNoConstraint(objWithIbaList, false);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void stitchFormDescriptionAttr(BigInteger workFlowContainerId) {
        List<IdentifierEntity> flowObjEntityList = commonService.getFlowObjListByWorkFlowContainer(workFlowContainerId);
        List<SaveObjIBADTO> objWithIbaList = new ArrayList<>();
        List<ObjRenameDTO> objRenameDTOS = new ArrayList<>();
        for (IdentifierEntity entity : flowObjEntityList) {
            TyplmFormDataVO formDataVO = this.tyFormDataExtService.getFormDataDetail(entity.getOid());
            JSONObject formData = formDataVO.getFormdata();
            List<FormDataDTO> formDataDTOS = FormDataDTO.convertToFormDataDTO(formData);
            StringBuffer sb = new StringBuffer();
            ObjRenameDTO objsRenameDTO = new ObjRenameDTO();
            objsRenameDTO.setOid(entity.getOid().toString());
            objsRenameDTO.setOtype(entity.getOtype());
            for (FormDataDTO formDataDTO : formDataDTOS) {
                String key = formDataDTO.getKey();
                Object value = formDataDTO.getValue();
                dealDescription(key, value, sb);
            }
            objsRenameDTO.setName(sb.toString());
            objRenameDTOS.add(objsRenameDTO);
            SaveObjIBADTO saveObjIBADTO = new SaveObjIBADTO();
            List<IbaDTO> ibaDTOList = new ArrayList<>();
            IbaDTO ibaDTO = new IbaDTO();
            ibaDTO.setKey("FormOverview");
            ibaDTO.setValue(sb.toString());
            ibaDTOList.add(ibaDTO);
            saveObjIBADTO.setObjIbaList(ibaDTOList);
            saveObjIBADTO.setCTyEntityBaseDO(new CTyEntityBaseDO(entity.getOid(), entity.getOtype()));
            objWithIbaList.add(saveObjIBADTO);
        }
        typlmObjsRenameService.batchRenameIdentityAndName(objRenameDTOS, false);
        log.info("----开始保存表单描述属性----:{}", objWithIbaList);
        typlmAttributeValueService.batchSaveIBAByObjsNoConstraint(objWithIbaList, false);
    }

    @Override
    public PageInfo<RTResultEntityVO> queryBomByCondition(SearchConditionDTO conditionDTO)
            throws InvocationTargetException, IllegalAccessException {
        PageInfo<ResultEntityVO> resultEntityVOPageInfo = typlmCommonSearchService.queryByConditionForPage(conditionDTO);
        List<ResultEntityVO> list = resultEntityVOPageInfo.getList();
        List<RTResultEntityVO> rtResultList = new ArrayList<>();
        for (ResultEntityVO vo : list) {
            RTResultEntityVO rtVo = new RTResultEntityVO();
            BeanUtils.copyProperties(rtVo, vo);
            String objectNumber = vo.getObjectNumber();
            BigInteger oid = vo.getOid();
            String view = vo.getView();
            List<PartBomTree> partBomTreeList = commonService.queryChildParts(objectNumber, oid.toString(), view, true, null, "N").getPartBomTreeList();
            PartBomTree partBomTree = partBomTreeList.get(0);
            List<BigInteger> ids = new ArrayList<>();
            dealChildOid(partBomTree,ids);
            Map<String, List<AttributeVO>> ibaMap = typlmAttributeValueService.getAttrValueTableByEntitys(ids, "ty.inteplm.cad.CTyCADDoc");
            HashSet<PartBomTree> children = partBomTree.getChildren();
            if(CollUtil.isNotEmpty(children)){
                dealChildren(partBomTree, ibaMap,rtVo);
            }
            rtResultList.add(rtVo);
        }

        // 创建新的 PageInfo 并拷贝分页信息
        PageInfo<RTResultEntityVO> result = new PageInfo<>();
        BeanUtils.copyProperties(result, resultEntityVOPageInfo); // 拷贝分页信息
        result.setList(rtResultList);
//        QueryBomVO queryBomVO = new QueryBomVO();
//        queryBomVO.setPageInfo(result);
//        queryBomVO.setColumn(conditionDTO.getColumns());
        return result;
    }

    private void dealChildOid(PartBomTree partBomTree, List<BigInteger> ids) {
        ids.add(new BigInteger(partBomTree.getPartoid()));
        HashSet<PartBomTree> children = partBomTree.getChildren();
        if(CollUtil.isNotEmpty(children)){
            for (PartBomTree child : children) {
                ids.add(new BigInteger(child.getPartoid()));
                dealChildOid(child, ids);
            }
        }
    }

    private void dealChildren(PartBomTree partBomTree, Map<String, List<AttributeVO>> ibaMap, RTResultEntityVO rtVo) {
        HashSet<PartBomTree> children = partBomTree.getChildren();
        if(CollUtil.isNotEmpty( children)){
            List<RTResultEntityVO> rtChildren = rtVo.getChildren();
            for (PartBomTree child : children) {
                RTResultEntityVO rtChild = new RTResultEntityVO();
                rtChild.setObjectNumber(child.getObjectNumber());
                rtChild.setName(child.getName());
                rtChild.setOid(child.getPartoid());
                rtChild.setView(child.getView());
                if(ibaMap.containsKey(child.getPartoid())){
                    rtChild.setIbaAttrs(ibaMap.get(child.getPartoid()));
                }
                rtChildren.add(rtChild);
                dealChildren(child, ibaMap, rtChild);
            }
        }
    }

    private void dealDescription(String key, Object value, StringBuffer sb) {
        if (key == null || value == null) {
            return;
        }

        // 处理以@开头的属性，作为IBA字段
        if (key.endsWith("#")) {
            sb.append(value);
        }

        // 处理嵌套对象
        if (value instanceof JSONObject) {
            handleJsonObject((JSONObject) value, sb);
        } else if (value instanceof JSONArray) {
            handleJsonArray((JSONArray) value, sb);
        }
    }

    private void dealValue(String key, Object value, List<IbaDTO> ibaDTOList) {
        if (key == null || value == null) {
            return;
        }

        // 处理以@开头的属性，作为IBA字段
        if (key.startsWith("@")) {
            String ibaName = key.substring(1);
            if (ibaName.endsWith("#")) {
                ibaName = ibaName.substring(0, ibaName.length() - 1);
            }
            IbaDTO ibaDTO = new IbaDTO();
            ibaDTO.setKey(ibaName);
            ibaDTO.setValue(value.toString());
            ibaDTOList.add(ibaDTO);
            return;
        }

        // 处理嵌套对象
        if (value instanceof JSONObject) {
            handleJsonObject((JSONObject) value, ibaDTOList);
        } else if (value instanceof JSONArray) {
            handleJsonArray((JSONArray) value, ibaDTOList);
        }
    }

    private void handleJsonObject(JSONObject jsonObject, List<IbaDTO> ibaDTOList) {
        if (jsonObject == null || jsonObject.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            dealValue(entry.getKey(), entry.getValue(), ibaDTOList);
        }
    }

    private void handleJsonObject(JSONObject jsonObject, StringBuffer sb) {
        if (jsonObject == null || jsonObject.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            dealDescription(entry.getKey(), entry.getValue(), sb);
        }
    }


    private void handleJsonArray(JSONArray jsonArray, List<IbaDTO> ibaDTOList) {
        if (jsonArray == null || jsonArray.isEmpty()) {
            return;
        }
        for (Object item : jsonArray) {
            if (item instanceof JSONObject) {
                handleJsonObject((JSONObject) item, ibaDTOList);
            }
        }
    }

    private void handleJsonArray(JSONArray jsonArray, StringBuffer sb) {
        if (jsonArray == null || jsonArray.isEmpty()) {
            return;
        }
        for (Object item : jsonArray) {
            if (item instanceof JSONObject) {
                handleJsonObject((JSONObject) item, sb);
            }
        }
    }

    @Resource
    private TyplmPrincipalService typlmPrincipalService;
    @Resource
    private TyplmOrgService typlmOrgService;
    @Resource
    private DeptRoleMapper deptRoleMapper;

    @Override
    public String getCurrentUserLeader() {
        BigInteger oid = TyAccountContext.getUser().getOid();
        PrincipalEntity principalEntity = new PrincipalEntity(oid, TableTypeConstrant.TY_USER_OTYPE);
        List<PrincipalEntity> outParent = typlmPrincipalService.getOneOutParentOrg(principalEntity);
        typlmOrgService.dealOrgParentPath(outParent);
        if (CollUtil.isEmpty(outParent)) {
            return "";
        }
        BigInteger deptId = null;
        for (PrincipalEntity entity : outParent) {
            if (entity instanceof OrgDO) {
                OrgDO orgDO = (OrgDO) entity;
                String containerotype = orgDO.getContainerotype();
                if (TableTypeConstrant.TY_ORGCONTAINER_OTYPE.equals(containerotype)) {
                    deptId = orgDO.getOid();
                }
            }
        }
        if(deptId == null){
            throw RTErrorCodeEnum.CUSTOM_EXCEPTION.getException("获取部门异常，请联系管理员");
        }
        List<DeptRoleDO> deptRoleDOS = deptRoleMapper.selectByLeaderByDeptId(String.valueOf(deptId));
        if(CollUtil.isEmpty(deptRoleDOS)){
            throw RTErrorCodeEnum.CUSTOM_EXCEPTION.getException("当前用户所在部门部门主管为空");
        }
        return deptRoleDOS.get(0).getUserName();
    }

    @Resource
    private TyplmDynamicFormService typlmDynamicFormService;
    @Resource
    private TyplmClassificationService typlmClassificationService;
    @Resource
    private TyplmTypeService typlmTypeService;
    @Resource
    private RTPartMapper rtPartMapper;
    @Resource
    private RTClassificationService classificationService;
    @Resource
    private RTAttributeCardMapper attributeCardMapper;
    @Resource
    private ProjectDevOrderMapper projectDevOrderMapper;

    @Override
    public PdmForm newGetPdmFormWithDataByType(PdmFormDTO dto) {
        try {
            Class<?> aClass = TyplmViewConfigUtil.getVoClassByVoName(dto.getVoName());
            String type = dto.getType();
            String view = dto.getPartView();
            String classificationOid = dto.getClassificationOid();
            PdmForm pdmFormWithData = this.typlmDynamicFormService.getPdmFormWithData(type, view, dto.getContainerOid(),
                                                                                      dto.getContainerOtype(), aClass,
                                                                                      dto.getFormLabel(),
                                                                                      classificationOid);
            List<PdmFormColumn> formData1 = pdmFormWithData.getFormData();
            for (PdmFormColumn formDatum : formData1) {
                String ibaEnName = formDatum.getIbaEnName();
                if ("ComponentCode".equals(ibaEnName)) {
                    formDatum.setReadOnly(true);
                }
            }
            if (StringUtil.isEmpty(classificationOid) || StringUtil.isBlank(classificationOid)) {
                return pdmFormWithData;
            }
            // 图样代号分类卡片
            TyplmClassificationEntityDTO currentClassInfo = typlmClassificationService.queryClassificationDTOByOID(
                    new BigInteger(classificationOid));
            if (currentClassInfo == null) {
                return pdmFormWithData;
            }
            String parentOid = currentClassInfo.getParentOid();
            List<String> types1 = Arrays.asList("MaterialCode", "PatternCode", "Standard", "EBOM_NUM");
            if (types1.contains(type)) {
                IdentifierEntity entity = new IdentifierEntity();
                if ("MaterialCode".equals(type)) {
                    //物料码分类卡片
                    TyplmClassificationEntityDTO parentClassInfo = typlmClassificationService.queryClassificationDTOByOID(
                            new BigInteger(parentOid));
                    if (parentClassInfo == null) {
                        return pdmFormWithData;
                    }
                    entity.setOid(new BigInteger(parentClassInfo.getId()));
                    entity.setOtype("ty.inteplm.type.CTyClassification");
                } else {
                    entity.setOid(new BigInteger(classificationOid));
                    entity.setOtype("ty.inteplm.type.CTyClassification");
                }
                DescribeSpliceRuleDO describeSpliceRuleDO = classificationService.queryAttrDescribeRule(entity);
                if (describeSpliceRuleDO != null) {
                    String describeRules = describeSpliceRuleDO.getDescribeRules();
                    String[] split = describeRules.split("_");
                    JSONObject rules = pdmFormWithData.getRules();
                    for (String key : split) {
                        if (rules.containsKey(key)) {
                            JSONArray rulesArray = rules.getJSONArray(key);
                            rulesArray.getJSONObject(0).put("required", true);
                        }
                    }
                }
            }
            List<String> types = Arrays.asList("MaterialCode", "PatternCode", "EBOM_NUM");
            if (!types.contains(type) || !"add".equals(dto.getFormLabel())) {
                return pdmFormWithData;
            }

            //物料码分类
            TyplmClassificationEntityDTO parentClassInfo = typlmClassificationService.queryClassificationDTOByOID(
                    new BigInteger(parentOid));
            if (parentClassInfo == null) {
                return pdmFormWithData;
            }

            Map<String, TyAttributeDefMapVO> tydhAttrMap = buildExclusiveAttrMap(currentClassInfo);

            Map<String, TyAttributeDefMapVO> wlmAttrMap = buildExclusiveAttrMap(parentClassInfo);


            if ("PatternCode".equals(type)) {
                // 如果是图样代号 置灰 物料码属性
                List<PdmFormColumn> formData = pdmFormWithData.getFormData();
                for (PdmFormColumn formColumn : formData) {
                    String ibaEnName = formColumn.getIbaEnName();
                    if (wlmAttrMap.containsKey(ibaEnName)) {
                        formColumn.setReadOnly(true);
                    }
                }
                String partNumber = dto.getPartNumber();
                PartDO partDO = rtPartMapper.queryLatestPartByNumberAndView(partNumber, view, null);
                if (partDO == null) {
                    return pdmFormWithData;
                }
                setPartIba(formData, partDO, type);
            } else if ("MaterialCode".equals(type)) {
                // 如果是物料码 图样代号属性 只读
                List<PdmFormColumn> formData = pdmFormWithData.getFormData();
                setReadOnlyAttributes(formData, tydhAttrMap);
                String patternCode = dto.getPatternCode();
                // 且将图样代号属性默认到物料码属性
                PartDO partDO = rtPartMapper.queryLatestPartByNumberAndView(patternCode.trim(), view, null);
                if (partDO != null) {
                    setPartIba(formData, partDO, type);
                }
            } else if ("EBOM_NUM".equals(type) /*|| "Standard".equals(type)*/) {
                String partNumber = dto.getPartNumber();
                PartDO partDO = rtPartMapper.queryLatestPartByNumberAndView(partNumber, view, null);
                if (partDO == null) {
                    return pdmFormWithData;
                }
                List<PdmFormColumn> formData = pdmFormWithData.getFormData();
                setPartIba(formData, partDO, type);
            }
            return pdmFormWithData;
        } catch (Exception e) {
            e.printStackTrace();
            throw RTErrorCodeEnum.PART_NOT_EXIST.getException(e.getMessage());
        }
    }

    private void setPartIba(List<PdmFormColumn> formData, PartDO partDO, String type) {
        Map<String, List<AttributeVO>> rootPartIba = typlmAttributeValueService.getAttrValueTableByEntitys(
                Collections.singletonList(partDO.getOid()), TableTypeConstrant.TY_PART_OTYPE);
        List<AttributeVO> attributeVOS = rootPartIba.get(partDO.getOid().toString());
        Map<String, String> ibaMap = new HashMap<>();
        for (AttributeVO attributeVO : attributeVOS) {
            String attributeName = attributeVO.getAttributeEnName();
            String attributeValue = attributeVO.getAttributeValue();
            ibaMap.put(attributeName, attributeValue);
        }
        for (PdmFormColumn formColumn : formData) {
            String prop = formColumn.getIbaEnName();
            if (ibaMap.containsKey(prop)) {
                if ("Description".equals(formColumn.getProp())) {
                    formColumn.setValue("");
                    formColumn.setReadOnly(true);
                    continue;
                }
                formColumn.setValue(ibaMap.get(prop));
                formColumn.setReadOnly(true);
            }
            if ("MaterialCode".equals(type)) {
                if ("PatternCodeDescription".equals(formColumn.getProp())) {
                    formColumn.setValue(ibaMap.get("Description"));
                    formColumn.setReadOnly(true);
                } else if ("Common_Attributes|1757215074349".equals(formColumn.getProp())) {
                    formColumn.setValue(ibaMap.get("CompleteDescription"));
                    formColumn.setReadOnly(true);
                } else if("PatternCodeName".equals(formColumn.getProp())){
                    formColumn.setValue(partDO.getName());
                    formColumn.setReadOnly(true);
                }else if("PatternCode".equals(formColumn.getProp())){
                    formColumn.setValue(partDO.getObjnumber());
                    formColumn.setReadOnly(true);
                }
            }else if("EBOM_NUM".equals(type)){
                if ("ProductSpectrumName".equals(formColumn.getProp())) {
                    formColumn.setValue(partDO.getName());
                    formColumn.setReadOnly(true);
                } else if("PatternCodeName".equals(formColumn.getProp())){
                    formColumn.setValue(partDO.getName());
                    formColumn.setReadOnly(true);
                }
            }
        }
    }

    private @NotNull Map<String, TyAttributeDefMapVO> buildExclusiveAttrMap(
            TyplmClassificationEntityDTO currentClassInfo) {
        List<TyAttributeDefMapVO> currentClassAttrDefMapList = this.typlmTypeService.queryInheritAttrDef(new BigInteger(
                currentClassInfo.getId()), currentClassInfo.getOtype());
        currentClassAttrDefMapList.forEach((attr) -> {
            attr.setIbaDefType(TyplmEntityBaseUtil.getAttributeTypeDisplay(attr.getIbaDefType()));
        });

        // 图样代号专有属性
        return currentClassAttrDefMapList.stream()
                .filter(attr -> "0".equals(attr.getIsInherit()))
                .collect(Collectors.toMap(
                        TyAttributeDefMapVO::getName,
                        Function.identity(),
                        (v1, v2) -> v1
                ));
    }

    private void setReadOnlyAttributes(List<PdmFormColumn> formData, Map<String, TyAttributeDefMapVO> attrMap) {
        for (PdmFormColumn formColumn : formData) {
            String ibaEnName = formColumn.getIbaEnName();
            if (attrMap.containsKey(ibaEnName)) {
                formColumn.setReadOnly(true);
            }
        }
    }

    @Override
    public List<String> selectMaterialAttrByClassId(String classId, String type) {
        if(type.contains("PatternCode")){
            TyplmClassificationEntityDTO currentClassInfo = typlmClassificationService.queryClassificationDTOByOID(
                    new BigInteger(classId));
            String parentOid = currentClassInfo.getParentOid();
            return typeClassMapper.selectIbaNameByClassId(parentOid);
        }
        return Collections.emptyList();
    }

    @Override
    public List<PartBomTree> queryEBom(String number, String type) {
        if(StringUtils.isBlank(type)){
            type = "EBOM_NUM";
        }
        List<PartBomTree> result = new ArrayList<>();
        String finalNumber = "%"+number+"%";
        List<JSONObject> partDetails = rtPartMapper.selectEBom(finalNumber, type);
        List<String> list = Arrays.asList("SegmNum", "Description", "ManufacturingAttr", "DefaultUnitMeasurement");
        List<JSONObject> objectList = attributeCardMapper.queryIbaAttrOIdByName(list);
        Map<String, String> ibaOieAndNameMap = objectList.stream().collect(
                Collectors.toMap(obj -> obj.getString("OID"), obj -> obj.getString("NAME")));
        if(CollUtil.isNotEmpty(partDetails)){
            for (JSONObject partDetail : partDetails) {
                String oid = partDetail.getString("OID");
                String partNumber = partDetail.getString("PARTNUMBER");
                List<PartBomTree> partBomTreeList = commonService.queryChildParts(partNumber, oid, "Design", true,null, "N", false).getPartBomTreeList();
                PartBomTree partBomTree = partBomTreeList.get(0);
                dealAttribute(partBomTree,ibaOieAndNameMap);
                result.add(partBomTree);
            }
        }
        return result;
    }

    @Override
    public JSONArray queryProjectCode() {
        JSONArray jsonArray = new JSONArray();
        List<ProjectDevOrderDO> projectDevOrderDOS = projectDevOrderMapper.queryAllDevOrder(null);
        for(ProjectDevOrderDO projectDevOrderDO : projectDevOrderDOS){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("projectCode", projectDevOrderDO.getProjectCode());//项目开发令
            jsonObject.put("projectName", projectDevOrderDO.getProjectName());//项目名称
            jsonObject.put("responsiblePerson", projectDevOrderDO.getResponsiblePerson());//项目经理
            jsonObject.put("devLevel", projectDevOrderDO.getDevLevel());//开发等级
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    private void dealAttribute(PartBomTree partBomTree, Map<String, String> ibaOieAndNameMap) {
        Map<String, List<String>> partIbaAttributeMap = partBomTree.getPartIbaAttributeMap();
        Map<String, List<String>> ibaAttributeMap = partBomTree.getIbaAttributeMap();
        if (CollUtil.isNotEmpty(partIbaAttributeMap)) {
            for (Map.Entry<String, String> stringStringEntry : ibaOieAndNameMap.entrySet()) {
                String key = stringStringEntry.getKey();
                if(partIbaAttributeMap.containsKey(key)){
                    partIbaAttributeMap.put(stringStringEntry.getValue(),partIbaAttributeMap.get(key));
                }else if(ibaAttributeMap.containsKey(key)){
                    ibaAttributeMap.put(stringStringEntry.getValue(),ibaAttributeMap.get(key));
                }
            }
        }
        HashSet<PartBomTree> children = partBomTree.getChildren();
        if (CollUtil.isNotEmpty(children)){
            for (PartBomTree child : children) {
                dealAttribute(child,ibaOieAndNameMap);
            }
        }
    }



}
